<?php

class PlaceManager extends TModule
{
	// -------------------- basic functions --------------------
	public function addPlace($name, $description = null, $address_id = null)
	{
		$place = new PlaceRecord();
		$place->setData(0, $name, $description, $address_id);
		
		if($place->save())
			return $place;
		else
			return null;
	}
	
	public function deletePlace($id)
	{
		return PlaceRecord::finder()->deleteById($id);
	}
	
	public function updatePlace($id, $name, $description, $address_id)
	{	
		$placeRecord = new PlaceRecord();
		$placeRecord->setData($id, $name, $description, $address_id);
		return $this->updatePlaceByPlaceRecord($placeRecord);
	}

	public function updatePlaceByPlaceRecord($placeRecord)
	{	
		if($placeRecord instanceof PlaceRecord)
		{
			$finder = PlaceRecord::finder();
			$id = $placeRecord->getId();
			if($id > 0 && $rec = $finder->findByPk($id))
			{
				if($rec->equals($placeRecord))
					return $rec;
				$rec->setDataByPlaceRecord($placeRecord);
				if($rec->save())
					return $rec;
			}
		}
		return null;
	}
	
	public function getPlaceById($id)
	{
		return PlaceRecord::finder()->findById($id);
	}
	
	// -------------------- extended functions --------------------
	public function getPlacesList($revert = false, $offset = -1, $limit = -1)
	{
		$criteria = new TActiveRecordCriteria();
		
		if($revert)
			;//$criteria->OrdersBy['registration'] = 'desc';
			
		if($offset < 0 || $offset == null)
			$offset = 0;
		if($limit < 0 || $limit == null)
			$limit = $this->countPlaces();
			
		$criteria->Offset = $offset;
		$criteria->Limit = $limit;
		
		return PlaceRecord::finder()->findAll($criteria);
	}
	
	public function countPlaces()
	{
		return PlaceRecord::finder()->count();
	}
}

?>